//导入express
const express = require("express")
//引入数据库对象
const connection = require(`${__dirname}/../mysql/index.js`)
//创建路由对象
const router = express.Router()

//执行数据库语句
function executeSql(sql,res){
    connection.query(sql,err=>{
        if(err){
            return res.send({code: 1, data: {}, msg: "服务器异常"})
        }
        res.send({code: 0,data: {},msg: "操作成功"})
    })
}

//添加反馈单
/*参数
* title String 必传 表单标题
* content String 可选 表单内容
* uid int 必传 用户id*/
router.get("/add_feedback",(req,res)=>{
    const {title,content,uid} = req.query
    if(title === undefined || title === "" || uid === undefined || uid === ""){
        return res.send({code: 1, data: {}, msg: "必传参数缺失"})
    }
    const sql = `insert into feedback(f_title,f_content,u_id) values("${title}","${content || ''}",${uid})`
    executeSql(sql,res)
})

//查询
/*参数
* fid int 可选 表单id
* uid int 可选 用户id
* 若无参数则查询所有*/
router.get("/get_feedback",(req,res)=>{
    const {fid,uid} = req.query
    const sql = `select * from feedback where 1 = 1 ${fid ? `and f_id = ${fid}` : ''} ${uid ? `and u_id = ${uid}` : ""}`
    connection.query(sql,(err,result)=>{
        if(err){
            return res.send({code: 1, data: {}, msg: "服务器异常"})
        }
        const feedbackList = []
        result.map(item=>{
            feedbackList.push({
                fid: item.f_id,
                title: item.f_title,
                content: item.f_content,
                recover: item.f_recover,
                status: item.f_status
            })
        })
        res.send({code: 0,data: {feedbackList},msg: "查询成功"})
    })
})

//修改
/*参数
* fid int 必传 表单id
* recover String 可选 回复内容
* status String 可选 表单状态*/
router.get("/update_feedback",(req,res)=>{
    const {fid,recover,status} = req.query
    if(fid === undefined || fid === ""){
        return res.send({code: 1, data: {}, msg: "必传参数缺失"})
    }
    const sql = `update feedback set
                f_id = ${fid}
                ${recover ? `,f_recover = "${recover}"` : ''}
                ${status ? `,f_status = "${status}"` : ''}
                where f_id = ${fid}`
    executeSql(sql,res)
})

//删除
/*参数
* fid int 必传 反馈单id*/
router.get("/delete_feedback",(req,res)=>{
    const {fid} = req.query
    if(fid === undefined || fid === ""){
        return res.send({code: 1, data: {}, msg: "必传参数缺失"})
    }
    const sql = `delete from feedback where f_id = ${fid}`
    executeSql(sql,res)
})

module.exports = router